#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

int main()
{
    pid_t id = fork();
    if (0 == id)
    {
        //让子进程被替换
        
        char* const envp[] =
        {
            (char*)"HELLO=111",
            NULL
        };
        char* const argv[] =
        {   
            //可变长数组, 存放参数
            (char*)"ls",  //const char*  --->>>   char*
            (char*)"-l",
            //(char*)"-a",
            NULL    //语法规定, 必须以NULL结尾
        };
        //execv("/usr/bin/ls", argv);
        //execvp("ls", argv);//只用指定指令名, 系统会自动在环境变量PATH中找路径
        
        extern char** environ;//类似指针数组的地址(但不一样)
        execvpe("ls", argv, environ);

        printf("swap failed!!\n");
    }
    else 
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        if (rid > 0)
        {
            //一直等待目标进程
            if (WIFEXITED(status))
            {
                //正常结束
                printf("child pid:%d, exit_code:%d\n", id, WEXITSTATUS(status));
            }
            else
            {
                //出现异常
                printf("child pid:%d, exit_signal:%d\n", id, status & 0x7f);
            }
        }
        else // -1 == rid
        {
           //出错 
        }
    }

    return 0;
}
